package cn.com.jdyun.controller;

import cn.com.jdyun.dto.UserCredit;
import cn.com.jdyun.interceptor.Auth;
import cn.com.jdyun.util.CodeUtil;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.QRCodeUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class IndexController {

    /**
     * 首页
     *
     * @return
     */
    @GetMapping({"", "/", "/index"})
    public String home() {
        return "index";
    }

    /**
     * 获取图形验证码
     *
     * @param session
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha")
    public void captcha(HttpSession session, HttpServletResponse response) throws IOException {
        CodeUtil.generateCodeAndPic(session, response);
    }

    /**
     * 获取我的推荐注册链接
     *
     * @param session
     * @param response
     * @throws IOException
     */
    @Auth
    @GetMapping("/qrcode")
    public void qrcode(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserCredit userCredit = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);
        String context = request.getHeader("Origin");
        if(context == null) {
        	context = request.getRequestURL().toString().replace(request.getServletPath(), "");
        }
        if(!context.endsWith("/")) {
        	context += "/";
        }
        String path = context + "register.html?Code=" + userCredit.getCode();
        System.out.println(">>> path: " + path);
        //File file = org.springframework.util.ResourceUtils.getFile("classpath:static/btc-icon.png");
        ClassPathResource resource = new ClassPathResource("static/btc-icon.png");
        InputStream inputStream = resource.getInputStream();
        QRCodeUtil.encode(path, inputStream, response.getOutputStream(), false);
    }

    @GetMapping("/regist")
    public String regist(@RequestParam(required = false) String refereeCode, Model model) {
        model.addAttribute(refereeCode, refereeCode);
        return "regist";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/forgetpwd")
    public String forgetpwd() {
        return "login";
    }
}
